import { forkCall, isRef } from '@/utils';
import { useCallback } from 'react';
import { useEffectRef, useMountedRef } from '.';

const useCall = (fn, ...args) => {
  const mountedRef = useMountedRef();
  const fnRef = useEffectRef([fn, ...args]);

  return useCallback((...nextArgs) => {
    // 如果绑定的参数是Ref对象，取ref.current
    let [refFn, ...refArgs] = fnRef.current.map((ref) => (isRef(ref) ? ref.current : ref));

    return forkCall(mountedRef, refFn, ...refArgs, ...nextArgs);
  }, []);
};

export default useCall;
